import os
import subprocess
import time
import argparse
import threading
import queue

def execute_command(command, command_queue):
    """执行单条命令并捕获输出"""
    try:
        result = subprocess.run(command, 
                              shell=True, 
                              check=True,
                              stdout=subprocess.PIPE, 
                              stderr=subprocess.STDOUT,
                              text=True,
                              encoding='utf-8',
                              errors='replace')
        command_queue.put(f"[SUCCESS] {command}\n{result.stdout}")
        return True
    except subprocess.CalledProcessError as e:
        command_queue.put(f"[FAILED] {command}\nExit code: {e.returncode}\nOutput: {e.stdout}")
        return False

def run_commands(commands, interval, iterations, log_file=None):
    """执行命令循环"""
    total_commands = len(commands) * iterations
    completed_commands = 0
    command_queue = queue.Queue()
    
    log_handler = open(log_file, 'a', encoding='utf-8') if log_file else None
    
    print(f"\n开始执行，共需完成 {total_commands} 次命令执行")
    
    for i in range(iterations):
        print(f"\n>>>> 开始第 {i+1}/{iterations} 轮迭代 >>>>")
        
        # 执行当前迭代的所有命令（不间隔）
        threads = []
        for cmd in commands:
            # 显示当前进度
            completed_commands += 1
            progress = completed_commands / total_commands * 100
            print(f"\n[{completed_commands}/{total_commands} ({progress:.1f}%)] 执行命令: {cmd}")
            
            # 创建并启动线程
            t = threading.Thread(
                target=execute_command,
                args=(cmd, command_queue),
                daemon=True
            )
            t.start()
            threads.append(t)
        
        # 等待所有命令线程完成
        for t in threads:
            t.join()
            
        # 处理所有输出
        while not command_queue.empty():
            output = command_queue.get()
            if log_handler:
                log_handler.write(output + "\n" + "-"*80 + "\n")
            print(output)
        
        print(f"\n<<<< 完成第 {i+1}/{iterations} 轮迭代 <<<<")
        
        # 仅在非最后一次迭代时等待
        if i < iterations - 1:
            print(f"\n等待 {interval} 秒后继续...")
            time.sleep(interval)

    if log_handler:
        log_handler.close()
    print("\n所有命令执行完成！")

def main():
    parser = argparse.ArgumentParser(description='定时循环执行命令工具')
    parser.add_argument('-c', '--commands', nargs='+', required=True,
                        help='要执行的命令列表（用空格分隔）')
    parser.add_argument('-i', '--interval', type=float, default=5.0,
                        help='每组命令执行间隔时间（秒），默认5秒')
    parser.add_argument('-n', '--iterations', type=int, default=1,
                        help='循环执行次数，默认1次')
    parser.add_argument('-l', '--log', type=str,
                        help='日志文件路径（记录所有命令输出）')
    
    args = parser.parse_args()
    
    print(f"\n命令执行计划:")
    print(f"  命令列表: {args.commands}")
    print(f"  组间间隔: {args.interval}秒")
    print(f"  循环次数: {args.iterations}")
    if args.log:
        print(f"  日志文件: {args.log}")
    print("-" * 60)
    
    try:
        run_commands(
            commands=args.commands,
            interval=args.interval,
            iterations=args.iterations,
            log_file=args.log
        )
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"\n发生错误: {str(e)}")

if __name__ == "__main__":
    main()